package muta.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import muta.bean.SqlBean;

import org.apache.log4j.Logger;

public class InterWeixin extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3194813672125865824L;

	public static Logger logger = Logger.getLogger(SqlBean.class.getName());

	public InterWeixin() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String signature = request.getParameter("signature");

		String timestamp = request.getParameter("timestamp");

		String nonce = request.getParameter("nonce");

		String echostr = request.getParameter("echostr");

		logger.debug("signature:" + signature + ";timestamp:" + timestamp
				+ ";nonce:" + nonce + ";echostr:" + echostr);

		String token = "169gold";

		String[] str = { token, timestamp, nonce };
		Arrays.sort(str);
		String bigStr = str[0] + str[1] + str[2];
		String digest = new SHA1().getDigestOfString(bigStr.getBytes())
				.toLowerCase();
		if (digest.equals(signature)) {
			response.setCharacterEncoding("utf-8");
			System.out.println(echostr);
			BufferedReader sis = request.getReader();
			char[] buf = new char[1024];
			int len = 0;
			StringBuffer sb = new StringBuffer();
			while ((len = sis.read(buf)) != -1) {
				sb.append(buf, 0, len);
			}
			response.setContentType("text/xml");
			response.getWriter()
					.print("<?xml version=\"1.0\"?><xml><ToUserName><![CDATA[o3B6FjkJtJB_VCQnbMH65lA_6l2s]]></ToUserName>"
							+ "<FromUserName><![CDATA[gh_53d680696bf4]]></FromUserName>"
							+

							"<CreateTime>1357449401</CreateTime>"
							+ "<MsgType><![CDATA[text]]></MsgType>"
							+ "<Content><![CDATA[爱人民币]]></Content>" + "</xml>");
			response.getWriter().print(echostr);

		}

	}

	public void init() throws ServletException {
	}

}